package com.zz.yt.lib.ui.base.mvp;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.base.delegate.BaseDelegate;
import com.whf.android.jar.base.mvp.BaseMvpDelegate;
import com.whf.android.jar.base.mvp.BasePresenter;
import com.whf.android.jar.base.mvp.IModel;
import com.whf.android.jar.base.mvp.IView;
import com.zz.yt.lib.annex.document.util.AnnexUtil;
import com.zz.yt.lib.ui.R;
import com.zz.yt.lib.ui.callback.RequestCodes;
import com.zz.yt.lib.ui.delegate.scanner.ScannerDelegate;
import com.zz.yt.lib.ui.listener.OnClickObjectListener;


import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/***
 * 动态权限注入
 * @author qf
 * @version 1.0
 * @date 2020-06-23
 */
@RuntimePermissions
public abstract class PerCheckerMvpFragment<M extends IModel, V extends IView, P extends BasePresenter<M, V>>
        extends BaseMvpDelegate<M, V, P> {

    //(选择文件)不是直接调用方法
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startFilePicker(@NonNull BaseDelegate delegate) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                ActivityUtils.startActivityForResult(Latte.getActivity(), intent, RequestCodes.REFRESH);
                return;
            }
        }
        AnnexUtil.Bundle()
                .setZip()
                .setContent(this)
                .setRequestCode(RequestCodes.FILE_PICKER)
                .onAddAnnexClickListener();
    }

    /**
     * @param delegate：选择文件
     */
    public void startFilePickerWithCheck(BaseDelegate delegate) {
        PerCheckerMvpFragmentPermissionsDispatcher.startFilePickerWithPermissionCheck(this, delegate);
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void startStoragePicker(@NonNull BaseDelegate delegate, BaseDelegate delegateStorage) {
        delegate.getSupportDelegate().startForResult(delegateStorage, RequestCodes.SIGNATURE);
    }

    /**
     * @param delegate：写入文件权限
     */
    public void startStoragePickerWithCheck(BaseDelegate delegate, BaseDelegate delegateStorage) {
        PerCheckerMvpFragmentPermissionsDispatcher.startStoragePickerWithPermissionCheck(this,
                delegate, delegateStorage);
    }

    /*********************************** CAMERA 拍照权限（二维码）**************************************/

    //扫描二维码(不直接调用)
    @NeedsPermission(Manifest.permission.CAMERA)
    void startScan(@NonNull BaseDelegate delegate) {
        delegate.getSupportDelegate().startForResult(new ScannerDelegate(), RequestCodes.SCAN);
    }

    /**
     * @param delegate：扫描二维码
     */
    public void startScanWithCheck(BaseDelegate delegate) {
        PerCheckerMvpFragmentPermissionsDispatcher.startScanWithPermissionCheck(this, delegate);
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void onCameraDenied() {
        ToastUtils.showLong("不允许拍照");
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void onCameraNever() {
        ToastUtils.showLong("永久拒绝拍照权限");
    }

    /***************************************** LOCATION 定位权限***************************************/

    //定位权限(不直接调用)
    @NeedsPermission({
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION})
    void startClick(OnClickObjectListener listener, boolean isNeedBack) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && isNeedBack) {
            //先申请前台定位权限，再申请后台单位权限
            PerCheckerMvpFragmentPermissionsDispatcher.startClickQbgWithPermissionCheck(this,
                    listener);
        } else {
            if (listener != null) {
                listener.onClick(null);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @NeedsPermission({Manifest.permission.ACCESS_BACKGROUND_LOCATION})
    void startClickQbg(OnClickObjectListener listener) {
        if (listener != null) {
            listener.onClick(null);
        }
    }

    /**
     * @param listener：定位
     */
    public void starClickWithCheck(OnClickObjectListener listener) {
        PerCheckerMvpFragmentPermissionsDispatcher.startClickWithPermissionCheck(this,
                listener, false);
    }

    /**
     * @param listener：定位权限
     */
    public void starClickWithCheck(OnClickObjectListener listener, boolean isNeedBack) {
        PerCheckerMvpFragmentPermissionsDispatcher.startClickWithPermissionCheck(this,
                listener, isNeedBack);
    }

    /**
     * @param delegate：定位
     */
    public void startLocationWithCheck(final BaseDelegate delegate, final BaseDelegate delegateLocation) {
        starClickWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                delegate.getSupportDelegate().startForResult(delegateLocation, RequestCodes.LOCATION);
            }
        });
    }


    /**
     * @param delegate：定位
     */
    public void startLocationWithCheck(final BaseDelegate delegate, final Class<? extends Activity> clz) {
        starClickWithCheck(new OnClickObjectListener() {
            @Override
            public void onClick(Object index) {
                ActivityUtils.startActivityForResult(delegate, clz, RequestCodes.LOCATION);
            }
        });
    }

    @OnPermissionDenied({
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION})
    void onLocationDenied() {
        ToastUtils.showLong("不允许定位");
    }

    @OnNeverAskAgain({
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION})
    void onLocationNever() {
        ToastUtils.showLong("永久拒绝定位权限");
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @OnPermissionDenied(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
    void onLocationBgDenied() {
        ToastUtils.showLong("不允许后台定位");
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @OnNeverAskAgain(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
    void onLocationBgNever() {
        ToastUtils.showLong("永久拒绝后台定位权限");
    }

    /******************************************* 权限回调 ******************************************/

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PerCheckerMvpFragmentPermissionsDispatcher.onRequestPermissionsResult(this,
                requestCode, grantResults);
    }

    //****************************************** 跳转 ********************************************/

    /**
     * @param delegate：跳转,返回可以刷新界面
     */
    protected void startForResult(BaseDelegate delegate) {
        startForResult(delegate, RequestCodes.REFRESH);
    }


}
